<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StorePolicyRequest;
use App\Http\Requests\UpdatePolicyRequest;
use App\Models\Policy;
use Illuminate\Http\Request;

class PolicyController extends Controller
{

    public function index(Request $request)
    {
        $title = $request->title;
        $readedTimes = $request->readedTimes;
        $policies = Policy::when($title, function ($query) use ($title) {
            $query->where('title', 'like', '%'.$title."%");
        })
            ->when($readedTimes, function ($query) use ($readedTimes) {
                $query->where('readedTimes', '>', $readedTimes);
            })
            ->orderByDesc('id')->paginate(10);
        return $policies;
    }


    public function store(StorePolicyRequest $request)
    {
        $request->validate(
            [
                'title' => ['required'],
                'preview' => ['required'],
                'content' => ['required']
            ]);
        Policy::create($request->input());
        return $this->message("添加成功");
    }


    public function show(Policy $policy)
    {
        return $policy;
    }


    public function update(UpdatePolicyRequest $request, Policy $policy)
    {
        $request->validate(
            [
                'title' => ['required'],
                'preview' => ['required'],
                'content' => ['required']
            ]);
        $policy->update($request->input());
        return $this->message('修改成功');
    }


    public function destroy(Policy $policy)
    {
        $policy->delete();
        return $this->message("删除成功");
    }
}
